<!DOCTYPE html>
<html lang="zh">
<head>
    <th:block th:include="include :: header('表单向导')" />
    <th:block th:include="include :: jquery-smartwizard-css" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-select-css" />

    <style type="text/css">
        /* 如果要让工具栏固定在页面底部,使用下面的样式,不需要的可以注释 */
        .sw>.toolbar-bottom{
            z-index: 100;
            bottom: 0px;
            left: 0;
            width: 100%;
            position: fixed;
            text-align: right;
            background: #fff;
            box-shadow: 0 -2px 6px 1px hsla(223,8%,83%,.5);
            border-top: 1px solid #e3e4e8;
        }
        /* 如果设置了是否自动调节高度为false,需要加滚动条 */
        .sw>.tab-content{
            overflow-x: hidden;
            overflow-y: auto;
        }
        /* 解决工具栏无法固定底部的问题（如果页面没有animated类可以不写这部分代码） */
        .animated {
            animation-fill-mode: none;
            -webkit-animation-fill-mode: none;
            -moz-animation-fill-mode: none;
            -o-animation-fill-mode: none;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight" style="height: 100%;">
    <div class="row">
        <form  id ="step1" class="form form-horizontal m-t">
            <input name="id"   hidden id = "id">

            <h4 class="form-header h4">基本信息</h4>
            <div class="form-group">
                <label class="col-sm-3 control-label">选择服务：</label>
                <div class="col-sm-8">
                    <select id="appServers"  class="form-control noselect2 selectpicker" data-none-selected-text="请选择" multiple>

                    </select>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">发布时间：</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" id="datetimepicker-demo-3" name = "pushTime"  placeholder="yyyy-MM-dd HH:mm:ss" required>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">任务名称：</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text"  name="taskName" id="taskName" required>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">发布声明：</label>
                <div class="col-sm-8">
                    <textarea type="text" name="taskDes" id = "taskDes" class="form-control" placeholder="请输入文本"></textarea>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">暂存路径：</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" readonly  disabled name="basicPath" id="basicPath" required>
                </div>
            </div>

            <h4 class="form-header h4">应用上传</h4>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">本次所有应用包：</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" readonly  disabled name="allUpload" id="allUpload" >
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">尚未上传的应用包：</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" readonly  disabled name="noUpload" id="noUpload" >
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label is-required">已经上传的应用包：</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" readonly  disabled name="hasUpload" id="hasUpload" >
                </div>
            </div>




            <h4 class="form-header h4">发布实例</h4>
            <div class="form-group">
                <label class="col-sm-3 control-label "></label>
                <div class="col-sm-8">
                    <table class="table" id="taskAppList">
                        <thead>
                        <tr>
                            <th>是否发布</th>
                            <th>任务Id</th>
                            <th>应用名称</th>
                            <th>发布服务器</th>
                            <th>应用包名</th>
                            <th>发布时间</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>




        <div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content animated bounceInRight">
                    <div class="modal-header">
                        <h4 class="modal-title">同时期任务</h4>
                    </div>
                    <div class="modal-body">
                        <div class="ibox float-e-margins">
                            <div class="ibox-title">
                                <h5>基本</h5>
                            </div>
                            <div class="ibox-content">

                                <table class="table" id="runTask">
                                    <thead>
                                    <tr>
                                        <th>任务名称</th>
                                        <th>任务描述</th>
                                        <th>发布时间</th>
                                        <th>当前状态</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table>

                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>

</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: jquery-smartwizard-js" />
<th:block th:include="include :: datetimepicker-js" />
<th:block th:include="include :: bootstrap-fileinput-js" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: bootstrap-select-js" />

<script th:inline="javascript">
    var taskId = [[${id}]];
    //0是新增，1是修改
    var updateFlag = [[${updateFlag}]];

    $(document).ready(function() {
        $.when(initAppGroupSelect(),initUpload()).then(function() {
            console.log("所有方法按顺序执行完毕");
            initBasicByTask()
        });
    });

    //更新下拉框
    function  initAppGroupSelect() {
        $.operate.ajaxGet(ctx+"app/listAppByGroup",function (data) {
            var html = "";
            $.each(data, function(key, value) {
                html +=  '<optgroup label="--请选择分组: '+value.groupName+'--">';
                $.each(value.appList, function(k2, v2) {
                    html +=  '<option value="'+v2.id+'">'+v2.appName+'</option>' ;
                });
                html+='</optgroup>';
            });
            $('#appServers').append(html);
            $('#appServers').selectpicker('refresh')
        })
    }

    //填充基础信息
    function  initBasicByTask() {
        $("#datetimepicker-demo-3").datetimepicker({
            format: "yyyy-mm-dd hh:ii:00",  // 设置日期时间格式
            autoclose: true,
            minuteStep: 30,  // 设置为每次只能选择30分钟步长
            startView: 2,  // 默认视图为月视图
            maxView: 2,    // 最大视图为月视图
            minView: 0     // 最小视图为小时视图
        });
        if(taskId == null){
            taskId = "";
        }
        putValueForBasicTask(taskId);

    }

    //加载上传文件
    function initUpload(){
        $("#multipleFile").fileinput({
            uploadUrl: ctx + 'tPushTaskApp/uploadJarFile',
            allowedFileExtensions: ['jar'],
            uploadAsync: false,
            layoutTemplates: {
                preview: '', // 移除预览框
            },
            uploadExtraData: function() {
                return   {basicPath:$("#basicPath").val(),taskId:$('#id').val(),appIdList:$('#appServers').val()};
            }
        }).on('fileloaded', function(event, file, previewId, index, reader) {
            // 文件加载时，显示文件名称
            var fileName = file.name;
            var previewContainer = $("#" + previewId);
            previewContainer.find(".file-caption-name").text(fileName);
        }).on('filebatchuploadsuccess', function(event, data, previewId, index) {
            if(data.response.code == web_status.SUCCESS){
                //获取到上传后的文件
                uploadSuccess(data.response.data);
                $.modal.alertSuccess("上传成功！")
                $("input[name='" + event.currentTarget.id + "']").val('');
            }else {
                $.modal.alertError(data.response.msg);
            }
        }).on('fileremoved', function(event, id, index) {
            // 移除文件后清空文件输入框的值
            $("input[name='" + event.currentTarget.id + "']").val('');
        }).on('change', function() {
            var validFiles = [];
            var fileNames = [];
            //获取到所有的文件名
            var files = $(this)[0].files;
            var  no =  $('#noUpload').val();
            if(no == ''){
                $.modal.alertError("当前无需要上传的文件，如需上传请选择应用！")
                return
            }
            //进行有效上传的限制
            var  jarFiles =  no.split(',');
            $.each(files, function(index, file) {
                if(jarFiles.includes(file.name)){
                    validFiles.push(file);
                    fileNames.push(file.name);
                }
            });
            if(validFiles.length == 0){
                $.modal.alertError("当前无需要上传的文件，如需上传请选择应用！")
                return;
            }
            $("input[name='" + event.currentTarget.id + "']").val(fileNames.join(","));
        });
    }

    //时间组件变化，验证数据
    $('#datetimepicker-demo-3').blur(function() {
        var pushTime = $("#datetimepicker-demo-3").val();
        if(pushTime == ''){
            $.modal.msgError("发布时间不能为空");
            return
        }
        if(new Date(pushTime) <= new Date()){
            $.modal.msgError("发布时间不能小于当前时间");
            return
        }
        //验证日期
        $.operate.ajaxGet(ctx+"task/listByDate?id="+$("#id").val()+"&dateStr="+pushTime,function (res) {
            if(res.length > 0){
                $.modal.confirm("查询发布时间内有允许任务，是否选中一个进行新增处理",function (data) {
                    $('#myModal').modal('show');
                    $('#taskAppList tbody').empty();

                    $.each(res,function (index,value) {
                        $('#runTask tbody').append(
                            '<tr>' +
                            '<td>' + value.taskName + '</td>' +
                            '<td>' + value.taskDes + '</td>' +
                            '<td>' + value.pushTime + '</td>' +
                            '<td>' + value.pushStepName + '</td>' +
                            '<td><a class="btn btn-danger btn-xs " href="javascript:void(0)" onclick="putValueForBasicTask(\'' + value.id + '\')"><i class="fa fa-dedent"></i>选中</a></td>' +
                            '</tr>'
                        );
                    });
                })
            }
        });
        return true;
    });

    //选择发布日期相同的数据
    function putValueForBasicTask(taskId){
        //删除原来的，防止重复
        if(updateFlag == 0 && taskId != ''){
            $.operate.ajaxGet(ctx+"task/removeOldTask?taskId="+$('#id').val());
        }
        $('#myModal').modal('hide');

        //添加基础数据
        $.operate.ajaxGet(ctx+"task/getById?id="+taskId,function (data) {
            //基础数据赋值
            $.each(data, function(key, value) {
                var inputElement = $('[name="' + key + '"]'); // 选择与对象属性名称相同的表单字段
                if (inputElement.length > 0) {
                    inputElement.val(value); // 设置表单字段的值
                }
                if(key == 'appServers'){
                    $('#appServers').val(value).selectpicker('refresh');
                }
                if(  updateFlag ==  1 && key == 'pushTime'){
                    inputElement.prop('disabled', true)
                }else {
                    inputElement.prop('disabled', false)
                }
            });

            //上传文件赋值
            setUploadInput($('#appServers').val());
            //应用实例
            selectTaskAppTable();
            //不可编辑
            $('input').prop('readonly', true);
            $('textarea').prop('readonly', true);
        })
    }

    //根据下拉选择需要上传的应用
    $('#appServers').on('change', function() {
        // 获取所有被选中的数据
        var selectedValues = $(this).val();
        setUploadInput(selectedValues);
    });

    function setUploadInput(selectedValues) {
        if(selectedValues.length == 0){
            $('#allUpload').val("");
            $('#noUpload').val("");
            $('#hasUpload').val("");
            return;
        }
        var param = {"appIds":selectedValues,"taskId":$('#id').val()};
        $.operate.postJSON(ctx + 'tPushTaskApp/findJars',JSON.stringify(param),function (res) {
            if(res.code == web_status.SUCCESS){
                $('#allUpload').val(res.data.all);
                $('#noUpload').val(res.data.noUpload);
                $('#hasUpload').val(res.data.hasUpload);

            }else {
                $.modal.alertError(res.msg);
            }
        })
    }

    //查询发布实例的表格
    function selectTaskAppTable() {
        var jsonData = {"taskId":$("#id").val()};
        $.operate.postJSON(ctx+"tPushTaskApp/list",JSON.stringify(jsonData),function (res) {
            $('#taskAppList tbody').empty();
            $.each(res.data,function (index,value) {
                $('#taskAppList tbody').append(
                    '<tr>' +
                    '<td>    <label class="check-box"> <input type="checkbox" disabled value="' + value.id + '" id="inlineCheckbox' + value.id + '" ' + (value.pushActive == 1 ? 'checked' : '') + '></label></td>' +
                    '<td>' + value.taskId + '</td>' +
                    '<td>' + value.appName + '</td>' +
                    '<td>' + value.serverIp + '</td>' +
                    '<td>' + value.appJarName + '</td>' +
                    '<td>' + value.pushTime + '</td>' +
                    '</tr>'
                );
            });
        })
    }

    //上传成功更新包信息
    function uploadSuccess(uploadFileNameArr) {
        var  no =  $('#noUpload').val();
        var  has = $('#hasUpload').val();
        if(has == ''){
            $('#hasUpload').val(uploadFileNameArr.join(","));
        }else {
            $('#hasUpload').val(has+","+uploadFileNameArr.join(","));
        }

        var noArr = no.split(",");
        for(var i = 0 ; i < noArr.length ;i++){
            if(uploadFileNameArr.includes(noArr[i])){
                noArr.splice(i,1);
            }
        }

        if(noArr.length == 0){
            $('#noUpload').val('');
        }else {
            $('#noUpload').val(noArr.join(","))
        }
        //执行查询发布
        selectTaskAppTable();
    }


    //保存
    function formVail(caoFlag) {
        debugger
        //参数校验
        //----发布应用
        if($('#appServers').val() == ''){
            $.modal.msgError("发布应用不能为空");
            return ;
        }
        if($('#taskName').val() == ''){
            $.modal.msgError("任务不能为空");
            return ;
        }
        if($('#taskDes').val() == ''){
            $.modal.msgError("发版声明不能为空");
            return ;
        }
        if(caoFlag == 1 && $('#noUpload').val() != ''){
            $.modal.msgError("尚有应用包未上传，无法发布");
            return ;
        }

        //----发布时间
        var pushTime = $("#datetimepicker-demo-3").val();
        if(pushTime == ''){
            $.modal.msgError("发布时间不能为空");
            return ;
        }
        if(new Date(pushTime) <= new Date()){
            $.modal.msgError("发布时间不能小于当前时间");
            return ;
        }

        //保存
        var formData = $("#step1").serializeArray();
        var jsonData = {};
        $.each(formData, function() {
            jsonData[this.name] = this.value;
        });
        //---选择应用
        var selectedValues = [];
        $('input[type="checkbox"]:checked').each(function() {
            selectedValues.push($(this).val());
        });
        jsonData["taskAppIds"] = selectedValues.join(",");
        jsonData["pushStep"] = caoFlag == 0?0:1;
        jsonData["pushTime"] = pushTime;
        //提交
        $.operate.postJSON(ctx+"task/saveTask",JSON.stringify(jsonData),function (res) {
            $.operate.successCallback(res);
        })
    }


</script>
</body>
</html>
